import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { User, Grid, Tickets } from "@element-plus/icons-vue";
import Layout from '~/views/layout/Layout.vue';
import LayoutClient from '~/views/layout/LayoutClient.vue';
import store from '~/store';
import service from '~/service';

const routes: RouteRecordRaw[] = [{
    path: '/login',
    component: () => import('~/views/login/Login.vue'),
    name: 'login'
},
{
    path: '/home',
    component: () => import('~/views/Home.vue'),
    name: 'home'
},
{
    path: '/client',
    component: LayoutClient,
    name: 'client',
    children: [{
        path: 'password',
        component: () => import('~/views/register/Password.vue'),
        name: 'clientPassword'
    },
    {
        path: 'member-register',
        component: () => import('~/views/register/MemberRegister.vue'),
        name: 'memberRegister'
    },
    {
        path: 'partner-register',
        component: () => import('~/views/register/PartnerRegister.vue'),
        name: 'partnerRegister'
    }]
}, {
    path: '/client/quote-price',
    component: () => import('~/views/product/QuotePrice.vue'),
    name: 'quotePrice'
}
]

const commonRoute = {
    path: '/common',
    component: Layout,
    redirect: '/common/account-active',
    meta: {
        isNeedLogin: true
    },
    name: 'common',
    children: [{
        path: 'account-active',
        component: () => import('~/views/common/AccountActive.vue'),
        name: 'accountActive',
        meta: {
            isNeedLogin: true
        }
    }]
}

const orderRoute = {
    path: '/order',
    component: Layout,
    redirect: '/order/list',
    name: 'order',
    meta: {
        icon: Grid,
        title: '订单管理',
        isMenuList: true,
        isNeedLogin: true,
        permission: ['admin','manager','business']
    },
    children: [{
        path: 'list',
        component: () => import('~/views/order/Order.vue'),
        name: 'orderList',
        meta: {
            title: '订单列表',
            isNeedLogin: true,
            permission: ['admin','manager','business']
        }
    }]
}

const userRoute = {
    path: '/user',
    component: Layout,
    redirect: '/user/list',
    name: 'user',
    meta: {
        icon: User,
        title: '用户管理',
        isMenuList: true,
        isNeedLogin: true,
        permission: ['admin','manager','business']
    },
    children: [{
        path: 'list',
        component: () => import('~/views/user/User.vue'),
        name: 'userList',
        meta: {
            title: '用户列表',
            isNeedLogin: true,
            permission: ['admin','manager','business']
        }
    }]
}

const businessRoute = {
    path: '/service',
    component: Layout,
    redirect: '/service/list',
    name: 'service',
    meta: {
        icon: Tickets,
        title: '业务管理',
        isMenuList: true,
        isNeedLogin: true,
        permission: ['admin','manager']
    },
    children: [{
        path: 'list',
        component: () => import('~/views/business/Business.vue'),
        name: 'businessList',
        meta: {
            title: '业务员列表',
            isNeedLogin: true,
            permission: ['admin','manager']
        }
    },
    {
        path: 'approve-business-parter',
        component: () => import('~/views/business/ApproveBusinessParter.vue'),
        name: 'approveBusinessParter',
        meta: {
            title: '业务合伙人审批',
            isNeedLogin: true,
            permission: ['admin']
        }
    },
    {
        path: 'approve-customerI-identity',
        component: () => import('~/views/business/ApproveCustomerIdentity.vue'),
        name: 'approveCustomerIdentity',
        meta: {
            title: '客户身份审批',
            isNeedLogin: true,
            permission: ['admin','manager']
        }
    }]
}

const router = createRouter({
    history: createWebHistory(),
    routes,
})

const hasPermission = (route: RouteRecordRaw, role: string) => {
    let ishasPermission = true
    if (route.meta && route.meta.permission) {
        if (!(route.meta.permission as any).includes(role)) {
            ishasPermission = false
        }
    }
    return ishasPermission
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], role: string): RouteRecordRaw[] => {
    return routes.filter(route => {
        return hasPermission(route, role)
    }).map(route => {
        route = { ...route }
        if (route.children) {
            route.children = filterAsyncRoutes(route.children, role)
        }
        return route
    })
}

router.addRoute(commonRoute)

router.beforeEach(async (to, from, next) => {
    const hasToken = !!window.sessionStorage.getItem('usename')
    if (hasToken) {
        if (to.path === '/login') {
            next('/')
        } else {
            if (to.name) {
                if (to.meta.permission === undefined) {
                    next()
                }
            }
            const hasRoles = store.state.role.code !== ''
            if (hasRoles) {
                if (to.name) {
                    next()
                } else {
                    next('/')
                }
            } else {
                const roleRes = await service.syetem.getRole();
                if (roleRes.code === 200) {
                    if (roleRes.data.role_code) {
                        store.commit('setRole', roleRes.data);
                        const permissionRoutes = filterAsyncRoutes([orderRoute, userRoute, businessRoute], store.state.role.code);
                        if (permissionRoutes.length > 0) {
                            for (let route of permissionRoutes) {
                                router.addRoute(route)
                            }
                            router.addRoute({
                                path: '/',
                                redirect: permissionRoutes[0].path
                            })
                        }
                        next({ ...to, replace: true })
                    } else {
                        router.addRoute({
                            path: '/',
                            redirect: '/common/account-active'
                        })
                        next('/')
                    }
                } else {
                    next('/login')
                }
            }
        }
    } else {
        if (to.name) {
            if (to.meta.isNeedLogin) {
                next('/login')
            } else {
                next()
            }
        } else {
            next('/login')
        }
    }
})

export default router